﻿/*******************************************************
Copyright © 2009 Active Technologies Group, Inc. (ATGi)

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*******************************************************/

using System;
using System.Linq;
using System.Net;
using CommunityServer.Components;
using facebook.Schema;
using ATGi.CS.Facebook.Components;
using System.Text;

namespace ATGi.CS.Facebook.Data
{
    public class FacebookUser : IFacebookUser
    {
        private IFacebookSession facebookSession;

        public FacebookUser(IFacebookSession session)
        {
            facebookSession = session;
        }

        #region IFacebookUser Members

        public bool IsValid 
        { 
            get { return ID != -1; } 
        }

        public long ID
        {
            get 
            {
                user u = facebookSession.GetUser();
                if (u != null && u.uid.HasValue) 
                    return u.uid.Value; 
                else 
                    return -1; 
            }
        }

        public string Name
        {
            get
            {
                user u = facebookSession.GetUser();
                return (u != null ? u.name : null);
            }
        }

        public string FirstName
        {
            get
            {
                user u = facebookSession.GetUser();
                return (u != null ? u.first_name : null);
            }
        }

        public string LastName
        {
            get
            {
                user u = facebookSession.GetUser();
                return (u != null ? u.last_name : null);
            }
        }

        public User CommunityUser
        {
            get {
                return FacebookUsers.GetCommunityUserFromFacebookUser(this.ID);
            }
        }

        public string ProfileImageUrl(FacebookProfileImageSize size)
        {
            user u = facebookSession.GetUser();
            if (u == null)
                return null;
            switch (size)
            {
                case FacebookProfileImageSize.Small:
                    return u.pic_small;
                case FacebookProfileImageSize.Normal:
                    return u.pic;
                case FacebookProfileImageSize.Large:
                    return u.pic_big;
                default:
                case FacebookProfileImageSize.Square:
                    return u.pic_square;
            }
        }

        public byte[] ProfileImage(FacebookProfileImageSize size)
        {
            // The System.Drawing.Image properties on the Facebook Developers Toolkit didn't work for me.
            user u = facebookSession.GetUser();
            if (u == null)
                return null;
            switch (size)
            {
                case FacebookProfileImageSize.Small:
                    return DownloadImage(u.pic_small);
                case FacebookProfileImageSize.Normal:
                    return DownloadImage(u.pic);
                case FacebookProfileImageSize.Large:
                    return DownloadImage(u.pic_big);
                default:
                case FacebookProfileImageSize.Square:
                    return DownloadImage(u.pic_square);
            }
        }

        private byte[] DownloadImage(string url)
        {
            if (string.IsNullOrEmpty(url))
                return null;
            WebClient webClient = new WebClient();
            Byte[] pictureBytes = webClient.DownloadData(url);
            return pictureBytes;
        }

        #endregion

    }

    public static class UserExtensions
    {
        public static bool IsFacebookUser(this User u)
        {
            using (var dc = KernelContainer.Get<FBDataContext>())
            {
                return (dc.FacebookUsers.Count(fu => fu.UserID == u.UserID) > 0);
            }
        }

        public static string FacebookEmailHash(this User u)
        {
            return String.Format("{0}_{1}", GetCrc32Hash(u.Email), GetMD5Hash(u.Email));
        }

        private static string GetCrc32Hash(string input)
        {
            input = input.Trim().ToLower();
            byte[] emailBytes = Encoding.UTF8.GetBytes(input);
            Crc32 crc = new Crc32();
            crc.ComputeHash(emailBytes);
            return crc.CrcValue.ToString();
        }

        private static string GetMD5Hash(string input)
        {
            input = input.Trim().ToLower();
            System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] bs = Encoding.UTF8.GetBytes(input);
            bs = x.ComputeHash(bs);
            StringBuilder s = new StringBuilder();
            foreach (byte b in bs)
            {
                s.Append(b.ToString("x2").ToLower());
            }
            return s.ToString();
        }
    }
}
